package NBT;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.zip.GZIPInputStream;

import javax.swing.JOptionPane;

public class MapChunk
{
	public File chunkfile;
	public TAG_Compound root;	
	public byte [] blocks;
	public int xPos,zPos;
 
	
	public MapChunk(File file) throws Exception
	{
		chunkfile=file;
		String name=file.getName();
		String[] f=name.split("\\.");
		xPos=Integer.parseInt(f[1],36);
		zPos=Integer.parseInt(f[2],36);
		
		GZIPInputStream stream=new GZIPInputStream(new FileInputStream(file));

		root=(TAG_Compound) NBT_Tag.make(stream);
		TAG_Compound level=(TAG_Compound) root.getElement("Level");
		
		TAG_Int x=(TAG_Int)level.getElement("xPos");
		TAG_Int z=(TAG_Int)level.getElement("zPos");
		
		if(x.value!=xPos || z.value!=zPos)
			throw new Exception("Position mismatch in name and content: "+xPos+"/"+zPos+" vs "+x.value+"/"+z.value);
		
		TAG_Byte_Array blocks=(TAG_Byte_Array)level.getElement("Blocks");
		
		int size=blocks.data.length;
		this.blocks=new byte[size];
		System.arraycopy(blocks.data, 0, this.blocks, 0, size);
		
		stream.close();
	}
	
	public static File getPath(File world_path, int x_pos, int z_pos) throws Exception
	{
		int tx=(x_pos%64+64)%64;
		int tz=(z_pos%64+64)%64;
		
		String x_dir=Integer.toString(tx%64, 36);
		String z_dir=Integer.toString(tz%64, 36);
		
		String x_name=Integer.toString(x_pos, 36);
		String z_name=Integer.toString(z_pos, 36);
		
		String dest=world_path.getCanonicalPath()+"/"+x_dir+"/"+z_dir+"/c."+x_name+"."+z_name+".dat";
		
		return new File(dest);
	}
	
	public static MapChunk load(File world_path, int x_pos, int z_pos) throws Exception
	{
		File chunkfile=getPath(world_path,x_pos,z_pos);
		
		if(!chunkfile.exists()) throw new Exception("file "+chunkfile.getCanonicalPath()+" doesn't exist");
		
		return new MapChunk(chunkfile);
	}
}